import {
  Body,
  Controller,
  Delete,
  Get,
  Headers,
  HttpException,
  HttpStatus,
  Param,
  ParseIntPipe,
  Post,
  Put,
  Query,
  Redirect,
  Render,
  Res,
  UseFilters,
} from '@nestjs/common';
import { UserService } from '../../shared/services/user.service';
import { ApiTags } from '@nestjs/swagger';
import { CreateUserDto, UpdateUserDto } from '../../shared/dtos/user.dto';
import { AdminExceptionFilters } from '../filters/admin-exception-filters';
import { UtilityService } from '../../shared/services/utility.service';
import { Response } from 'express';
import { ParseOptionalIntPipe } from '../../shared/pipes/parse-optional-int.pipe';

@UseFilters(AdminExceptionFilters)
@ApiTags('用户view')
@Controller('admin')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly utilityService: UtilityService,
  ) {}

  @Get('user-list')
  @Render('user/user-list')
  async getFindAll(
    @Query('keyword') keyword: string = '',
    @Query('pageNo', new ParseOptionalIntPipe(1)) pageNo: number = 1,
    @Query('pageSize', new ParseOptionalIntPipe(5)) pageSize: number = 5,
  ) {
    return await this.userService.findAllPage(keyword, pageNo, pageSize);
  }

  @Get('user-create')
  @Render('user/user-create')
  async createUser() {
    return {
      user: {},
    };
  }

  // 重指向到 /admin/user-list
  @Post('api-user-create')
  @Redirect('/admin/user-list')
  async createApi(@Body() createUserDto: CreateUserDto) {
    // 加密密码
    if (createUserDto.password) {
      createUserDto.password = await this.utilityService.hashPassword(
        createUserDto.password,
      );
    }
    await this.userService.create(createUserDto);
    return {
      success: true,
    };
  }

  @Get('user/:id/edit')
  @Render('user/user-edit')
  async editUser(@Param('id', ParseIntPipe) id: number) {
    const user = await this.userService.findOne({ where: { id } });
    if (!user) {
      throw new HttpException('User not found', HttpStatus.NOT_FOUND);
    }
    return user;
  }

  @Put('api-user/:id/edit')
  // @Redirect()
  async editUserApi(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateUserDto: UpdateUserDto,
    @Headers('accept') accept: string,
    @Res() res: Response,
  ) {
    if (updateUserDto.password) {
      updateUserDto.password = await this.utilityService.hashPassword(
        updateUserDto.password,
      );
    } else {
      delete updateUserDto.password;
    }
    await this.userService.update(id, updateUserDto);
    // 更新状态也使用该接口，判断返回值是否json，不是则重指向view页面
    if (accept.includes('application/json')) {
      return res.json({ success: true });
    } else {
      return res.redirect('/admin/user-list');
    }
  }

  @Delete('api-user/:id/delete')
  async deleteUserApi(@Param('id', ParseIntPipe) id: number) {
    return await this.userService.delete(id);
  }
}
